import { defineStore } from 'pinia'
import { ref } from 'vue'
import { type QuoteRecord } from '@/api/quote/types'
import { getListApi, doAddApi, doUpdateApi, doDeleteApi, getFinishCountApi } from '@/api/quote'
import store from '@/store'
import { tableDataStore } from './dataStore'
import daysjs from 'dayjs'

export const historyDataStore = defineStore('historydata', () => {
  // 创建 processorStore 的引用（非实例化）
  let processor: ReturnType<typeof tableDataStore>
  const historyList = ref<QuoteRecord[]>([])
  const historyActive = ref<number>(-1)
  const serial_number = ref<number | string>('***********')
  const currentDate = daysjs()
  const historyDate = ref(currentDate.format('YYYY-MM-DD'))
  const unfinished = ref<number>(0)
  const finished = ref<number>(0)
  // activeTab = 'complete' | 'record'
  const activeTab = ref<string>('record')
  const initProcessor = () => {
    if (!processor) processor = tableDataStore() // ✅ 惰性实例化
  }

  const getHistoryList = async () => {
    let isFinish = 1
    if (activeTab.value == 'complete') {
      isFinish = 2
    }
    const res = await getListApi({
      create_time: historyDate.value,
      isFinish: isFinish
    })
    historyList.value = res.data
  }

  const addHistory = async (obj: { text: string; name: string }) => {
    const res = await doAddApi({
      title: obj.name,
      text: obj.text
    })

    if (res.code === 200) {
      resetSerialNumber()
      return true
    } else {
      return false
    }
  }

  const updateHistory = async (obj: { id: number; text: string; name: string }) => {
    const res = await doUpdateApi({
      id: obj.id,
      title: obj.name,
      text: obj.text
    })
    if (res.code === 200) {
      return true
    } else {
      return false
    }
  }

  const deleteHistory = async (id: number) => {
    const res = await doDeleteApi({ id: id })
    if (res.code === 200) {
      await initProcessor() // 惰性实例化
      await processor.clearLists()
      await getHistoryList()
      await getFinishCount()
      await resetSerialNumber()
    }
    return res
  }

  const getFinishCount = async () => {
    const res = await getFinishCountApi({
      create_time: historyDate.value
    })
    unfinished.value = res.data.unfinished
    finished.value = res.data.finished
  }

  const initHistory = () => {
    historyList.value = []
    historyActive.value = -1
  }

  // 点击事件获取当前选中的历史记录，并传给tableDataStore
  const clickHistoryActive = (index: number) => {
    initProcessor() // 惰性实例化
    historyActive.value = index
    const data = historyList.value[index]
    processor.getLists(data.text)
    serial_number.value = data.serial_number
  }

  const getHistoryActive = () => {
    return historyActive.value
  }
  const getHistoryActiveItem = () => {
    return historyList.value[historyActive.value]
  }

  const resetHistoryActive = () => {
    initProcessor() // 惰性实例化
    processor.clearLists()
    resetHistoryActives()
    resetSerialNumber()
  }
  const resetSerialNumber = () => {
    serial_number.value = '***********'
  }
  const getSerialNumber = () => {
    return serial_number.value
  }
  const resetHistoryActives = () => {
    historyActive.value = -1
  }

  return {
    serial_number,
    historyList,
    historyActive,
    getHistoryList,
    addHistory,
    updateHistory,
    deleteHistory,
    initHistory,
    clickHistoryActive,
    resetHistoryActive,
    getHistoryActive,
    getHistoryActiveItem,
    resetSerialNumber,
    getSerialNumber,
    historyDate,
    activeTab,
    getFinishCount,
    unfinished,
    finished
  }
})

/** 在 setup 外使用 */
export function historyDataStoreHook() {
  return historyDataStore(store)
}
